<template>
  <div>
    <van-sticky>
      <van-nav-bar title="百慕大影城" left-text="返回" left-arrow>
        <template #right>
          <van-popover
            v-model:show="showPopover"
            :actions="actions"
            placement="bottom-end"
          >
            <template #reference>
              <van-icon name="apps-o" size="22" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
      <!-- 滚动播报 -->
      <!-- <van-notice-bar
      left-icon="volume-o"
      text="无论我们能活多久，我们能够享受的只有无法分割的此刻，此外别无其他。"
    /> -->
      <!-- AppHeader广告栏 牛掰 语法糖 大小写自动识别-->
      <app-header></app-header>

      <!-- 顶部导航 -->
      <div class="nav">
        <p>北京</p>
        <span class="arrow"></span>
        <!-- 标签组 -->
        <van-tabs class="tabs" color="#f03d37" v-model:active="navActive">
          <van-tab title="热映" name="1"></van-tab>
          <van-tab title="待映" name="2"></van-tab>
          <van-tab title="经典" name="3"></van-tab>
        </van-tabs>
        <van-icon
          class="icon"
          name="search"
          style="font-weight: bold"
          size="25"
          color="#f03d37"
        />
      </div>
    </van-sticky>
    <van-pull-refresh
      v-model="refreshing"
      success-text="刷新成功"
      @refresh="onPullRefresh"
    >
      <!-- 电影列表 components文件 -->
      <van-list
        v-if="movies && movies.length > 0"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了，不要再滑了"
        @load="onLoad"
      >
        <movie-item
          @click="router.push(`/detail/${item.id}`)"
          v-for="item in movies"
          :key="item.id"
          :movie="item"
        ></movie-item>
      </van-list>
      <van-empty v-else>暂无数据</van-empty>
    </van-pull-refresh>

    <div style="height: 50px"></div>
  </div>
</template>

<script setup lang="ts">
import httpApi from "@/http";
import Movie from "@/types/Movie";
import { useRouter } from "vue-router";
import { ref, onMounted, reactive, watch } from "vue";
import "vant/es/image-preview/style";

const router = useRouter(); // 获取路由管理器

// 处理页面挂载完毕后，自动加载热映类别下的首页电影列表数据
const movies = reactive<Movie[]>([]);
onMounted(() => {
  //   发送请求,加载数据 myaxios
  let params = { cid: 1, page: 1, pagesize: 20 };
  httpApi.movieApi.queryByCategoryId(params).then((res) => {
    // 将res.data.data.result中保存的电影数组交给template渲染
    movies.push(...res.data.data.result);
  });
});

// 顶部标题栏相关组件
const showPopover = ref(false);

// 通过 actions 属性来定义菜单选项
const actions = ref([{ text: "首页" }, { text: "热点" }, { text: "新闻" }]);

// 顶部导航栏相关
const navActive = ref("1");
// 处理顶部导航选中项的变化，更新列表数据
watch(navActive, (newval, olaval) => {
  // 切换时滚动条默认滚动到顶部
  window.scrollTo(0, 0);
  finished.value = false;

  // 先去缓存中寻找，是否已经存过，如果有则不发请求了
  let str = localStorage.getItem(newval);
  if (str != null) {
    let data: Movie[] = JSON.parse(str);
    movies.splice(0, movies.length, ...data);
    return;
  }

  // newval就是选中类别的id
  // 整理参数发送请求
  let params = { cid: parseInt(newval), page: 1, pagesize: 20 };
  httpApi.movieApi.queryByCategoryId(params).then((res) => {
    console.log("换个类别加载电影列表", res);
    // splice(删除起始位置,删除多少个元素，替换成其他元素)
    movies.splice(0, movies.length, ...res.data.data.result);

    // 处理客户端缓存，将下载的数据存到LocalStorage中
    let value = JSON.stringify(res.data.data.result); //数组转字符串
    localStorage.setItem(newval, value);
  });
});

// 处理列表的触底加载
const loading = ref(false);
const finished = ref(false);
// 当触底后执行 onload方法 vant将会自动设置loading=true
// 在次数发送请求，访问当前类别的下一页数据
// 获取响应后，追加到原数组末尾 loading = false
const onLoad = function () {
  console.log("onload....");
  // 整理参数
  let cid = parseInt(navActive.value); // 转为数字
  let page = Math.floor(movies.length / 20) + 1;
  let params = { cid, page, pagesize: 20 };
  httpApi.movieApi.queryByCategoryId(params).then((res) => {
    console.log(`第${page}页数据`, res);
    movies.push(...res.data.data.result);
    loading.value = false; // 关闭正在加载中的状态
    // 判断是否到底
    if (movies.length == res.data.data.total) {
      finished.value = true;
    }
  });
};

// 处理列表的下拉刷新
const refreshing = ref(false);
const onPullRefresh = function () {
  console.log("下拉刷新...");
  // 加载当前类别下的首页数据，并且更新替换当前列表，更新缓存
  let params = { cid: parseInt(navActive.value), page: 1, pagesize: 20 };
  httpApi.movieApi.queryByCategoryId(params).then((res) => {
    movies.splice(0, movies.length, ...res.data.data.result);
    finished.value = false;
    refreshing.value = false;
    // 更新缓存
    localStorage.setItem(navActive.value, JSON.stringify(res.data.data.result));
  });
};
</script>

<!-- CSS -->
<style scoped>
.nav {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 0px 15px;
  border-bottom: 1px solid #e2e2e2;
  background-color: white;
}
.nav .arrow {
  display: block;
  border: 5px solid transparent;
  border-top-color: black;
  margin-top: 4px;
  margin-left: 5px;
}
.nav .tabs {
  flex: 1;
  margin: 0 20px;
}
</style>
<style>
:root:root {
  --van-nav-bar-background: #f03d37;
  --van-nav-bar-title-text-color: #fff;
  --van-nav-bar-icon-color: #fff;
  /* 左边返回*/
  --van-nav-bar-text-color: #fff;
}
</style>
